<?php
namespace app\controller;

use think\App;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\exception\ValidateException;

/**
 *AAD回调
 */
class Callback
{


    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;


    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;
    }



    public function index()
    {
        $auth = new \OneLogin\Saml2\Auth();

        $auth->processResponse(null);

        $errors = $auth->getErrors();

        if (!empty($errors)) {
            echo '<p>',implode(', ', $errors),'</p>';
            if ($auth->getSettings()->isDebugActive()) {
                echo '<p>'.htmlentities($auth->getLastErrorReason()).'</p>';
            }
        }

        if (!$auth->isAuthenticated()) {
            echo "<p>Not authenticated</p>";
            exit();
        }
        $data = [];
        $data['samlUserdata'] = $auth->getAttributes();
        $data['samlNameId'] = $auth->getNameId();
        $data['samlNameIdFormat'] = $auth->getNameIdFormat();
        $data['samlNameIdNameQualifier'] = $auth->getNameIdNameQualifier();
        $data['samlNameIdSPNameQualifier'] = $auth->getNameIdSPNameQualifier();
        $data['samlSessionIndex'] = $auth->getSessionIndex();

        $attributes = $data['samlUserdata'];

        $user = [];
        foreach ($attributes as $attributeName => $attributeValues) {
            foreach ($attributeValues as $attributeValue) {
                array_push($user, $attributeValue);
            }
        }

        try {

            $result = Db::name('admin_user')
//                ->where('givenname', '=', $user[6])
//                ->where('surname', '=', $user[7])
                ->where('email', '=', strtoupper($user[8]))
                ->field('givenname, surname, role_id, id, status, email')
                ->find();

            if ($result) {
                if ($result['status'] != 1) {
                    return redirect((string)url('Login/locking'))->send();exit;
                } else {

                    //更新管理员状态
                    $param = [
                        'last_login_ip' => request()->ip(),
                        'last_login_time' => time()
                    ];

                    Db::name('admin_user')->where('id', '=', $result['id'])->update($param);
                    session('admin_auth', $result);
                    session('aad', $data);
                    return redirect('/');
                }
            } else {
                return redirect((string)url('Login/error'))->send();exit;
            }

        } catch (\Exception $ex) {
            return json(['code' => 500, 'data' => '', 'msg' => $ex->getMessage()]);
        }
    }
}